package com.lfy.ai.kimi;

import com.alibaba.dashscope.common.Message;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.lfy.ai.AiGroupNorm;
import com.lfy.modules.common.custom.constants.AIEnum;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * KIMI 分组管理
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/6/28 15:40
 */
@Slf4j
public class KimiGroupDialogue implements AiGroupNorm {
    private Cache<String, Map<Integer, CopyOnWriteArrayList<Message>>> KIMI_DIALOGUE;
    private AtomicInteger groupId = new AtomicInteger(0);
    {
      log.info("Blog-web Kimi分组管理器启动中...");
    }
    @PostConstruct
    public void init() {
        KIMI_DIALOGUE =  Caffeine.newBuilder()
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .initialCapacity(32)
                .maximumSize(10_000)
                .build();
    }

    @Override
    public  int initLogin(String clientId) {
        Map<Integer, CopyOnWriteArrayList<Message>> map = new ConcurrentHashMap<>(4);
        int id = groupId.incrementAndGet();
        map.put(id, new CopyOnWriteArrayList<Message>());
        KIMI_DIALOGUE.put(clientId, map);
        return id;
    }


    @Override
    public  Integer createGroup(String clientId) {
        Map<Integer, CopyOnWriteArrayList<Message>> map = getMap(clientId);
        int id = groupId.incrementAndGet();
        map.put(id, new CopyOnWriteArrayList<Message>());
        return id;
    }

    @Override
    public  Map<Integer, CopyOnWriteArrayList<Message>> getMap(String clientId) {
        Map<Integer, CopyOnWriteArrayList<Message>> map = KIMI_DIALOGUE.getIfPresent(clientId);

        if (map == null) {
            throw new IllegalArgumentException("client not exist");
        }
        return map;
    }




    @Override
    public List<Message> getMessages(String clientId, Integer groupId) {
        Map<Integer, CopyOnWriteArrayList<Message>> map = getMap(clientId);
        return map.get(groupId);
    }
    @Override
    public  void putMessage(String clientId, Integer groupId, Message message) {

        Map<Integer, CopyOnWriteArrayList<Message>> map = getMap(clientId);
        Optional.ofNullable(map.get(groupId)).ifPresent(list -> {
            //删除最早的消息
            if(list.size() > MAX_HISTORY_SIZE){
                list.remove(0);
            }
            list.add(message);
        });
    }

    @Override
    public int getModelId() {
        return AIEnum.AiModel.KimiAi.getCode();
    }

}
